package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;

/**
 * Created by xuweijie on 2017/6/17.
 */
public class WebsocketChatServer {
    private static final Logger LOG=Logger.getLogger(WebsocketChatServer.class);

    public static final int WEBSOCKET_PORT = 9090;


    public void run(int port) throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).
                    channel(NioServerSocketChannel.class)
                    .childHandler(new WebsocketChatServerInitializer());
            // 绑定端口，开始接收进来的连接
            Channel channel = b.bind(port).sync().channel();
            LOG.info("WebSocket 已经启动，端口：" + port + ".");
            // 等待服务器 socket 关闭 。
            channel.closeFuture().sync();
        } finally {
            //优雅退出,释放资源
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}
